export default {
	namespaced: true,
	state() {
		return {
			carts: uni.getStorageSync('carts') || []
		}
	},
	getters: {
		cartCount(state) {
			// 购物车中商品数量统计
			return state.carts.length
		},
		allChecked(state) {
			return state.carts.every(item => item.goods_state)
		},
		checkdeCount(state) {
			return state.carts.reduce((count, item) => {
				// 果如商品是为选中的那不参与计算
				if (!item.goods_state) return count
				// 将商品数量累加
				return count += item.goods_number
			}, 0)
		},
		amount(state) {
			return state.carts.reduce((amount, item) => {
				if (!item.goods_state) return amount
				return amount += item.goods_price * item.goods_number
			}, 0)
		}
	},
	mutations: {
		// 更新购物车
		updateToCart(state, goods) {
			state.carts = goods
			this.commit('m_cart/saveToStorage')
		},
		addToCart(state, goods) {
			// console.log(state.carts)
			// console.log(goods)

			// 如果购物车中存在了相同的商品那就不要继续添加了
			// 而是将其数量加 1

			// 查找购物车中相同的商品
			let result = state.carts.find(item => item.goods_id === goods.goods_id)
			if (!result) {
				// 如果没有找到相同的
				state.carts.push(goods)
			} else {
				// 如果找到相同的
				result.goods_number += 1
			}

			// 存入本地
			this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state) {
			// 将购物车数据存入本地
			uni.setStorageSync('carts', state.carts)
		},
		toggleState(state, index) {
			// 切换选中状态
			state.carts[index].goods_state = !state.carts[index].goods_state
			this.commit('m_cart/saveToStorage')
		},
		toggleAll(state, goods_state) {
			state.carts.forEach(item => item.goods_state = !goods_state)
			this.commit('m_cart/saveToStorage')
		},
		// 将商品的数量减一
		decCount(state, index) {
			if (state.carts[index].goods_number <= 1) return
			state.carts[index].goods_number--
			this.commit('m_cart/saveToStorage')
		},
		addCount(state, index) {
			state.carts[index].goods_number++
			this.commit('m_cart/saveToStorage')
		}
	}
}
